package com.cmcc.groupcontacts.firewall.activity;

import java.util.ArrayList;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cmcc.groupcontacts.firewall.activity.strategy.WindowTitleStrategy;
import com.cmcc.groupcontacts.firewall.adapter.FirewallConfigKeywordsAdapter;
import com.cmcc.groupcontacts.firewall.business.FirewallConfigBusiness;
import com.cmcc.groupcontacts.firewall.dao.model.KeywordsVO;
import com.cmcc.groupcontacts.util.DialogUtil;
import com.cmcc.groupcontacts.util.ValidationUtil;
import com.yinhai.activity.R;

/**
 * 拦截关键字设置Activity
 * 
 * @author
 * 
 */
public class FirewallConfigKeywordsActivity extends BaseListActivity {
	private FirewallConfigBusiness firewallConfigBiz;

	private View clickedItem;
	private KeywordsVO clickedKeywords;

	@Override
	public void setTitleStrategy() {
		titleStrategy = new WindowTitleStrategy(this);
	}

	@Override
	public void setTitleButtons() {
		// 左边的“返回”按钮
		getLeftLayout().addView(createBackButton());

		// 右边的“新增”按钮
		final ImageButton btnAdd = createAddButton();
		btnAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				clickedItem = null;
				clickedKeywords = null;
				showKeywordsEdit();
			}
		});
		getRightLayout().addView(btnAdd);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.firewall_config_keywords_activity);

		init();
	}

	private void init() {
		registerForContextMenu(getListView());
		getListView().setOnItemLongClickListener(
				new AdapterView.OnItemLongClickListener() {
					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id) {
						clickedItem = view;
						clickedKeywords = (KeywordsVO) parent
								.getItemAtPosition(position);
						getListView().showContextMenu();
						return true;
					}
				});
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		clickedItem = v;
		clickedKeywords = (KeywordsVO) l.getItemAtPosition(position);
		showKeywordsEdit();
	}

	/*
	 * 添加/编辑信息拦截关键字
	 */
	private void showKeywordsEdit() {
		final View layout = getLayoutInflater().inflate(
				R.layout.firewall_config_keywords_edit, null);
		final TextView editKeywords = (TextView) layout
				.findViewById(R.id.edit_keywords);
		final boolean isInsert = (clickedKeywords == null);
		Builder builder = new Builder(this);
		if (isInsert) {
			// 新增
			builder.setTitle("添加");
		} else {
			// 编辑
			editKeywords.setText(clickedKeywords.getKeywords());
			builder.setTitle("编辑");
		}
		builder.setView(layout);
		builder.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DialogUtil.closeDialog(dialog, false);

						FirewallConfigKeywordsActivity context = FirewallConfigKeywordsActivity.this;
						String keywordsValue = editKeywords.getText()
								.toString();
						if (ValidationUtil.isNullOrEmpty(keywordsValue)) {
							Toast.makeText(context, "关键字不允许为空",
									Toast.LENGTH_SHORT).show();
							return;
						} else if (firewallConfigBiz.get(keywordsValue) != null) {
							Toast.makeText(context, "此关键字已经存在",
									Toast.LENGTH_SHORT).show();
							return;
						} else {
							DialogUtil.closeDialog(dialog, true);

							if (isInsert) {
								// 新增
								KeywordsVO keywords = new KeywordsVO();
								keywords.setKeywords(keywordsValue);
								if (firewallConfigBiz.insert(keywords) >= 0) {
									// TODO: [优化]更改为不刷新，直接notify的方式
									load();
									Toast.makeText(context, R.string.insert_ok,
											Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(context,
											R.string.insert_fail,
											Toast.LENGTH_SHORT).show();
								}
							} else {
								// 编辑
								clickedKeywords.setKeywords(keywordsValue);
								if (firewallConfigBiz.update(clickedKeywords) >= 0) {
									getBaseAdapter().notifyDataSetChanged();
									Toast.makeText(context, R.string.insert_ok,
											Toast.LENGTH_SHORT).show();
								} else {
									Toast.makeText(context,
											R.string.insert_fail,
											Toast.LENGTH_SHORT).show();
								}
							}
						}
					}
				});
		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DialogUtil.closeDialog(dialog, true);
					}
				});
		builder.show();
	}

	@Override
	protected void onResume() {
		super.onResume();

		load();
	}

	private void load() {
		// 设置无数据时的提示信息
		setEmptyText("");

		// 异步加载信息拦截关键字
		new KeywordsLoadTask().execute((Void[]) null);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.setHeaderTitle(clickedKeywords.getKeywords());
		menu.add(0, 1, Menu.NONE, "编辑");
		menu.add(0, 2, Menu.NONE, "删除");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			showKeywordsEdit();
			break;
		case 2:
			clickedItem.findViewById(R.id.btn_delete).performClick();
			break;
		}
		return super.onContextItemSelected(item);
	}

	/*
	 * 异步加载信息拦截关键字
	 */
	private class KeywordsLoadTask extends
			AsyncTask<Void, Integer, ArrayList<KeywordsVO>> {
		public KeywordsLoadTask() {
		}

		@Override
		protected ArrayList<KeywordsVO> doInBackground(Void... params) {
			firewallConfigBiz = new FirewallConfigBusiness();
			return firewallConfigBiz.getKeywordsList();
		}

		@Override
		protected void onPostExecute(ArrayList<KeywordsVO> keywordsList) {
			if (!ValidationUtil.isNullOrEmpty(keywordsList)) {
				setListAdapter(new FirewallConfigKeywordsAdapter(
						FirewallConfigKeywordsActivity.this, keywordsList));
			} else {
				setListAdapter(null);
			}
		}
	}
}
